﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

namespace GrpcDemo
{
    public static class ExtFile
    {
        public static bool ExistDirectory(string path)
        {
            return Directory.Exists(path);
        }

        public static bool ExistFile(string path)
        {
            return File.Exists(path);
        }
        public static string ReadFile(string path, Encoding encoding)
        {
            if (!ExistFile(path)) return string.Empty;
            return File.ReadAllText(path, encoding);
        }
        public static string ReadFile(string path)
        {
            if (!ExistFile(path)) return string.Empty;
            return File.ReadAllText(path, Encoding.UTF8);
        }

        public static string[] GetFiles(string path, string searchPattern, SearchOption opt = SearchOption.AllDirectories)
        {
            if (!ExistDirectory(path)) return null;
            return Directory.GetFiles(path, searchPattern, opt);
        }

        public static void WriteFile(string path, string content, Encoding encoding = null)
        {
            if (encoding == null) encoding = Encoding.UTF8;
            string dire = Path.GetDirectoryName(path);
            if (!ExistDirectory(dire)) Directory.CreateDirectory(dire);
            File.WriteAllText(path, content, encoding);
        }

        public static void DeleteFile(string path)
        {
            File.Delete(path);
        }

        /// <summary>
        /// 删除文件夹以及文件
        /// </summary>
        /// <param name="directoryPath"> 文件夹路径 </param>
        /// <param name="fileName"> 文件名称 </param>
        public static void DeleteDirectory(string directoryPath, string fileName)
        {

            //删除文件
            for (int i = 0; i < Directory.GetFiles(directoryPath).ToList().Count; i++)
            {
                if (Directory.GetFiles(directoryPath)[i] == fileName)
                {
                    File.Delete(fileName);
                }
            }

            //删除文件夹
            for (int i = 0; i < Directory.GetDirectories(directoryPath).ToList().Count; i++)
            {
                if (Directory.GetDirectories(directoryPath)[i] == fileName)
                {
                    Directory.Delete(fileName, true);
                }
            }
        }
        public static string GetApplicationStartPath()
        {

            return Path.GetDirectoryName(typeof(ExtFile).Assembly.Location);
        }
    }
}
